<?php

namespace App\Console\Commands;

use App\Http\Models\Mysql\SsyJstPurchaseinOrderEmbroideryCountTable;
use App\Http\Models\Mysql\SsyJstPurchaseinOrderTable;
use App\Http\Models\Mysql\SsyReconciliationOrderZgTable;
use Illuminate\Console\Command;

class reconciliationXH extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'command:reconciliationXH {--r_years=}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '创建对账单--绣花暂估';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $lastMonth = $this->option("r_years") ?? date('Y-m', strtotime("- 1 month"));
        $field = ["processing_code", "type_no", "contract_machining_price", "embroidery_factory_id", "brand_code"];
        $returnList = (new SsyJstPurchaseinOrderEmbroideryCountTable())->where('r_years', $lastMonth)->where('embroidery_factory_id', '<>', '')->get($field)->toArray();
        $supplierList = [];
        //组合 工厂+品牌 维度下的所有加工单
        foreach($returnList as $item){
            $supplierList[$item['embroidery_factory_id']][$item['brand_code']][] = $item;
        }
        $brandOrg = [
            "S" => "3090235", //SSY十三余
            "Y" => "10010"    //YXRG有香如故
        ];
        foreach($supplierList as $factoryId => $processingList){
            foreach ($brandOrg as $code => $sourceFactoryId){
                if(!isset($processingList[$code])){
                    continue;
                }
                $processingPriceMap = array_column($processingList[$code], null, "processing_code");
                $renumber = "DZ".$factoryId.str_replace("-", "", $lastMonth).time()."-A";
                $data = [
                    "renumber" => $renumber,
                    "recon_time" => $lastMonth,
                    "source_factory_groups_id" => $sourceFactoryId,//所属公司 区分公司对账
                    "supplier_id" => $factoryId, //供应商编码
                    "detail" => [],
                    "num" => 0,
                    "create_time" => date('Y-m-d H:i:s'),
                ];
                $exists = (new SsyReconciliationOrderZgTable())->where('recon_time', $lastMonth)->where('supplier_id', $factoryId)
                    ->where('source_factory_groups_id', $sourceFactoryId)->exists();
                if($exists){
                    echo "该工厂绣花暂估对账单, 已存在: ".$factoryId." ".$lastMonth."\n";
                    continue;
                }
                $processCodes = array_column($processingList[$code], "processing_code");
                $firstDay = date('Y-m-01 00:00:00', strtotime($lastMonth));
                $lastDay = date("Y-m-t 23:59:59", strtotime($lastMonth));
                $purchaseinList = (new SsyJstPurchaseinOrderTable())->whereBetween('ke_date', [$firstDay, $lastDay])->whereIn('processing_code', $processCodes)
                    ->get(["processing_code","sku_id","qty"])->toArray();
                $detail = [];
                foreach($purchaseinList as $item){
                    $data['num'] += $item['qty'];
                    $key = $item['processing_code']."_".$item['sku_id'];
                    if(isset($detail[$key])){
                        $detail[$key]['qty'] += $item['qty'];
                    }else{
                        $detail[$key] = [
                            'processing_code' => $item['processing_code'],
                            'contract_machining_price' => $processingPriceMap[$item['processing_code']]['contract_machining_price'], //暂估价传大货价
                            'type_no' => $processingPriceMap[$item['processing_code']]['type_no'],
                            'sku_code' => $item['sku_id'],
                            'qty' => $item['qty']
                        ];
                    }
                }
                $data['detail'] = json_encode(array_values($detail));
                (new SsyReconciliationOrderZgTable())->createData($data);
                echo "绣花暂估对账单已创建: ".$factoryId." ".$lastMonth."\n";
            }
        }
    }
}
